﻿/** 
 * Description:商品基本信息DAO
 * Date:2011-7-16
 * Author:Along	
*/
package com.community.shopping.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.community.shopping.domain.Goods;
import com.community.shopping.service.logic.Page;


public class GoodsDao extends HibernateDaoSupport{
	private Log log = LogFactory.getLog(GoodsDao.class);  
	

	public void save(Goods goods){
		getHibernateTemplate().saveOrUpdate(goods);	
		log.debug("-------保存一行goods-------");
	}

	public void delete(Goods goods){		  
		getHibernateTemplate().delete(goods);
		log.debug("---------删除一行goods-------");
	}


	public List<?> getGoods() {  		
	 return getHibernateTemplate().find(" from Goods"); 
	 }

	public List<?> getGoods(String sql){
		String finalsql="from Goods where "+sql;
		return getHibernateTemplate().find(finalsql);
	}   
	
	
	public List<?> getGoods(String sql,Page page){
		String finalsql="from Goods where "+sql;
		if(StringUtils.isNotBlank(page.getOrderBy()))
		{
			finalsql=finalsql+" order by "+page.getOrderBy();
			if(StringUtils.isNotBlank(page.getOrder()))
			{
				finalsql=finalsql+" "+page.getOrder();
			}
		}
		else
		{
			finalsql=finalsql+" order by goodType,sort";
			
		}
		Query   query   = this.getSession().createQuery(finalsql); 
		query.setFirstResult(page.getPageStartRow()>0?page.getPageStartRow()-1:0); 
		query.setMaxResults(page.getPageSize()); 
		if(page.getTotalRowsAmount()==0)
		{
		page.setTotalRowsAmount(getTotalCount(finalsql));
		}
		List   stu   =   query.list(); 
		return stu;
	} 
	
	public List<?> getHotGoods(String sql,Page page,Integer num){
		String finalsql="from Goods where "+sql;
		Query   query   = this.getSession().createQuery(finalsql+" order by saleNum desc"); 
		query.setFirstResult(page.getPageStartRow()>0?page.getPageStartRow()-1:0); 
		query.setMaxResults(page.getPageSize()); 
		if(page.getTotalRowsAmount()==0)
		{
		page.setTotalRowsAmount(num);
		}
		List   stu   =   query.list(); 
		return stu;
	}   
	
	public int getTotalCount(String sql)
	{
		Query   query   = this.getSession().createQuery("select count(*) "+sql); 
		int i=Integer.parseInt(query.list().get(0).toString());
		return i;
	}
	
	public Goods getGoodsById(Integer id){
		return getHibernateTemplate().get(Goods.class, id);
	}
	}

